package org.codefinger.json.parser.converter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.codefinger.json.parser.JSONArrayDeserializer;
import org.codefinger.json.parser.JSONConverter;
import org.codefinger.json.parser.JSONConverterType;
import org.codefinger.json.parser.JSONDeserializer;
import org.codefinger.json.parser.JSONObjectDeserializer;
import org.codefinger.json.parser.JSONParser;
import org.codefinger.json.util.magic.MagicAttribute;
import org.codefinger.json.util.magic.MagicPojo;

public class ConverterFromPojo implements JSONConverter {

	private PojoFieldConverter[]	fieldConverters;

	public ConverterFromPojo(Class<?> pojoClass) {
		MagicPojo<?> magicPojo = MagicPojo.getMagicPojo(pojoClass);
		List<PojoFieldConverter> list = new ArrayList<PojoFieldConverter>();
		Iterator<MagicAttribute> iterator = magicPojo.getMagicAttributes();
		MagicAttribute magicAttribute;
		while (iterator.hasNext()) {
			magicAttribute = iterator.next();
			list.add(new PojoFieldConverter(magicAttribute,//
					JSONParser.getConverter(magicAttribute.getField().getGenericType())));
		}
		fieldConverters = list.toArray(new PojoFieldConverter[list.size()]);
	}

	@Override
	public Object convert(Object value, JSONDeserializer deserializer) {
		return null;
	}

	@Override
	public Object convert(Object value, JSONObjectDeserializer objectDeserializer) {
		for (PojoFieldConverter fieldConverter : fieldConverters) {
			fieldConverter.setItem(value, objectDeserializer);
		}
		return objectDeserializer.getDeserializedValue();
	}

	@Override
	public Object convert(Object value, JSONArrayDeserializer arrayDeserializer) {
		return null;
	}

	@Override
	public void setItemValue(Object value, JSONObjectDeserializer objectDeserializer) {

	}

	@Override
	public void addItemValue(Object value, JSONArrayDeserializer arrayDeserializer) {

	}

	@Override
	public JSONConverterType jsonConverterType() {
		return JSONConverterType.Object;
	}

}
